<template>
  <view>
    <van-popup :show="props.voiceShow" custom-style="width:64%" @close="voiceClose">
      <view class="bg-white c-pd c-br pt-10 pb-10 w-full">
        <view class="voiceIcon text-align-center">
          <i class="i-icon-park-solid:voice w-20 h-20 c-color" @longpress="voiceStart" @touchend="voiceEnd"></i>
          <view class="my-2 c-text-16"> 状态：{{ state.voiceStateText }} </view>
          <view class="mt-2 c-text-14 c-red-6">长按图标开始录音，松手录音结束</view>
        </view>
      </view>
    </van-popup>
  </view>
</template>

<script setup lang="ts">
import useModal from '@/hooks/useModal';
interface IProps {
  voiceShow: boolean;
}

interface IState {
  voiceStateText: string;
  resultText: string;
  voiceShow: boolean;
}
type EmitEvents = {
  (event: 'onConfirm', data: { text: string; show: boolean }): void;
  (event: 'onCancel', data: {}): void;
  (event: 'onClose'): void;
};

const props = defineProps<IProps>();

const emits = defineEmits<EmitEvents>();

const plugin = requirePlugin('WechatSI');

const manager = plugin.getRecordRecognitionManager();

const { showModal } = useModal();

const state = reactive<IState>({
  voiceShow: false,
  voiceStateText: '未开始',
  resultText: '',
});

onMounted(() => {
  initRecord();
});

const voiceClose = () => {
  emits('onClose');
};

const voiceStart = () => {
  uni.authorize({
    scope: 'scope.record',
    success: function () {
      manager.start({
        duration: 60000,
        lang: 'zh_CN',
      });
    },
    fail: function () {
      showModal(
        '需要获取您的录音权限，请前往设置中授权',
        {
          success: (res) => {
            if (res.confirm) {
              uni.openSetting();
            }
          },
        },
        '请求录音权限',
      );
    },
  });
};

const voiceEnd = () => {
  manager.stop();
  state.voiceStateText = '未开始';
  setTimeout(() => {
    emits('onConfirm', {
      text: state.resultText,
      show: false,
    });
  }, 1000);
};

/**
 * 初始化语音识别回调
 * 绑定语音播放开始事件
 */
const initRecord = () => {
  manager.onStart = function (res: any) {
    if (res.msg === 'Ok') {
      state.voiceStateText = '正在录音';
    }
  };
  //有新的识别内容返回，则会调用此事件
  manager.onRecognize = (res: any) => {
    state.resultText = res.result;
  };

  // 识别结束事件
  manager.onStop = (res: any) => {
    state.resultText = res.result;
  };

  // 识别错误事件
  manager.onError = (res: any) => {
    showModal(res.msg);
  };
};
</script>
